{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.1. 生成数据集"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d76f567159d8aa0c"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l\n",
    "\n",
    "true_w = torch.tensor([2, -3.4])\n",
    "true_b = 4.2\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:25:01.897185Z",
     "start_time": "2024-03-28T09:24:57.909531Z"
    }
   },
   "id": "b101a43a6be9d30d",
   "execution_count": 1
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.2. 读取数据集"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "64cfaba31237df70"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "def load_array(data_arrays, batch_size, is_train=True):  #@save\n",
    "    \"\"\"构造一个PyTorch数据迭代器\"\"\"\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = load_array((features, labels), batch_size)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:26:14.588305Z",
     "start_time": "2024-03-28T09:26:14.574657Z"
    }
   },
   "id": "2fdd90d49a810a7b",
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "[tensor([[-1.2066, -0.3197],\n         [-0.3822, -0.8010],\n         [-1.5547,  0.6841],\n         [ 0.9506,  1.5421],\n         [ 2.2842, -0.1474],\n         [ 1.0177, -0.6904],\n         [-0.4067, -0.2825],\n         [ 0.7813, -0.1559],\n         [ 2.4801,  0.5358],\n         [ 0.0679, -0.5153]]),\n tensor([[ 2.8814],\n         [ 6.1494],\n         [-1.2328],\n         [ 0.8592],\n         [ 9.2605],\n         [ 8.5735],\n         [ 4.3401],\n         [ 6.2952],\n         [ 7.3336],\n         [ 6.1094]])]"
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(iter(data_iter))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:26:45.382555Z",
     "start_time": "2024-03-28T09:26:45.366264Z"
    }
   },
   "id": "a1d6c1b77bd43430",
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.3. 定义模型"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "d7b66ca37674ad9f"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "# nn是神经网络的缩写\n",
    "from torch import nn\n",
    "\n",
    "net = nn.Sequential(nn.Linear(2, 1))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:28:15.253242Z",
     "start_time": "2024-03-28T09:28:15.237652Z"
    }
   },
   "id": "a601907750dde88f",
   "execution_count": 5
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.4. 初始化模型参数"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "b6b1bf0d5c2ca323"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([0.])"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net[0].weight.data.normal_(0, 0.01)\n",
    "net[0].bias.data.fill_(0)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:29:31.776516Z",
     "start_time": "2024-03-28T09:29:31.756138Z"
    }
   },
   "id": "a32d19cc39982870",
   "execution_count": 6
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.5. 定义损失函数"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "cfe72da36ca40adb"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "loss = nn.MSELoss()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:30:16.783922Z",
     "start_time": "2024-03-28T09:30:16.775938Z"
    }
   },
   "id": "4ba075f7e743c76a",
   "execution_count": 8
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.6. 定义优化算法"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "9fa1931bf03a6ba3"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "trainer = torch.optim.SGD(net.parameters(), lr=0.03)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:33:20.533296Z",
     "start_time": "2024-03-28T09:33:20.519945Z"
    }
   },
   "id": "15649eaff5b33e5b",
   "execution_count": 9
  },
  {
   "cell_type": "markdown",
   "source": [
    "### 3.3.7. 训练"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "38b50008b0e7f219"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.000165\n",
      "epoch 2, loss 0.000098\n",
      "epoch 3, loss 0.000098\n"
     ]
    }
   ],
   "source": [
    "num_epochs = 3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in data_iter:\n",
    "        l = loss(net(X), y)\n",
    "        trainer.zero_grad()\n",
    "        l.backward()\n",
    "        trainer.step()\n",
    "    l = loss(net(features), labels)\n",
    "    print(f'epoch {epoch + 1}, loss {l:f}')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:37:00.627883Z",
     "start_time": "2024-03-28T09:37:00.371635Z"
    }
   },
   "id": "77efebb169c6b00",
   "execution_count": 12
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差： tensor([ 6.9666e-04, -6.2227e-05])\n",
      "b的估计误差： tensor([-0.0001])\n"
     ]
    }
   ],
   "source": [
    "w = net[0].weight.data\n",
    "print('w的估计误差：', true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print('b的估计误差：', true_b - b)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-28T09:37:12.514821Z",
     "start_time": "2024-03-28T09:37:12.496190Z"
    }
   },
   "id": "97212fecfeffa63c",
   "execution_count": 13
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   },
   "id": "9a49e9c9ff401641"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
